package com.gwclh.personnel.common.aop;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gwclh.personnel.common.annotation.OperLog;
import com.gwclh.personnel.entity.OperationLog;
import com.gwclh.personnel.service.IOperationLogService;
import com.gwclh.personnel.shiro.AccountProfile;
import com.gwclh.personnel.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Aspect
@Component
@Slf4j
public class OperLogAspect {

    @Autowired
    IOperationLogService logService;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.gwclh.personnel.common.annotation.OperLog)")
    public void operLogPointCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描(除登录控制器)所有controller包下操作
     */
    @Pointcut("execution(* com.gwclh.personnel.controller..*.*(..)) && !execution(* com.gwclh.personnel.controller.LoginController.*(..))")
    public void operExceptionLogPointCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPointCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        OperationLog operlog = null;
        try {
            operlog = convertResult(joinPoint);
            operlog.setOperRespParam(JSONUtil.toJsonStr(keys)); // 返回结果
            operlog.setOperResult(true);
            logService.save(operlog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPointCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        OperationLog operlog = null;
        try {
            operlog = convertResult(joinPoint);
            operlog.setOperExcName(e.getClass().getName());
            operlog.setOperExcMsg(stackTraceToString(e.getClass().getName(), e.getMessage()));
            operlog.setOperResult(false);
            logService.save(operlog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }


    }

    private OperationLog convertResult(JoinPoint joinPoint) throws Exception {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        OperationLog operlog = new OperationLog();

        // 从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的方法
        Method method = signature.getMethod();
        // 获取操作
        OperLog opLog = method.getAnnotation(OperLog.class);
        if (opLog != null) {
            String operModule = opLog.operModule();
            String operType = opLog.operType();
            String operDesc = opLog.operDesc();
            String remark = opLog.remark();
            operlog.setOperModule(operModule); // 操作模块
            operlog.setOperType(operType); // 操作类型
            operlog.setOperDesc(operDesc); // 操作描述
            operlog.setRemark(remark); // 备注
        }

        // 获取当前操作员信息
        AccountProfile accountProfile = ShiroUtil.getProfile();
        operlog.setOperUserId(accountProfile.getId()); // 请求用户ID
        operlog.setOperUserName(accountProfile.getUsername());

        // 获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        // 获取请求的方法名
        String methodName = method.getName();
        methodName = className + "." + methodName;
        operlog.setOperMethod(methodName); // 请求方法


        String requestMethod = operlog.getOperType();

        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod) || HttpMethod.DELETE.name().equals(requestMethod))
        {
            String params = argsArrayToString(joinPoint.getArgs());
            operlog.setOperRequParam(StringUtils.substring(params, 0, 2000));
        }else{
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSONUtil.toJsonStr(rtnMap);
            operlog.setOperRequParam(params); // 请求参数
        }


        // 请求IP
        String ip = request.getRemoteAddr();
        if (ip != null) {
            operlog.setOperIp(ip);
        }

        operlog.setOperUri(request.getRequestURI()); // 请求URI
        return operlog;
    }


    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage) {
        StringBuffer strbuff = new StringBuffer();
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (int i = 0; i < paramsArray.length; i++)
            {
                if (!isFilterObject(paramsArray[i]))
                {
                    if(paramsArray[i] instanceof List){
                        params +=   JSONUtil.toJsonStr(paramsArray[i]);
                    }else{
                        Object jsonObj = JSONUtil.parseObj(paramsArray[i]);
                        params += jsonObj.toString() + " ";
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o)
    {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }

}
